const https = require('https')
const cheerio = require('cheerio')
const download = require('download')
const path = require('path')
const fs = require('fs')

// 抓取的目标站
let url = 'https://www.ui.cn'

let dirpath = path.resolve('./uploads')

// 请求
https.get(url, {
  headers: {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3780.0 Safari/537.36'
  }
}, res => {
  let html = []
  res.on('data', chunk => html.push(chunk))
  res.on('end', () => {
    html = Buffer.concat(html).toString()
    // html内容加载到cheerio库中
    const $ = cheerio.load(html)

    // 选图片
    $('.post img').each(function (i, el) {
      let imgUrl = $(this).attr('data-original')
      if (imgUrl) {
        // 请求的请求地址
        imgUrl = 'http:' + imgUrl
        download(imgUrl).then(buffer => {
          let filename = path.join(dirpath, i + '.png')
          fs.writeFileSync(filename, buffer)
        })
      }
    })

  })
})



